package com.link.base.base.sms.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.link.base.user.model.CoreUser;
import com.link.base.base.sms.dao.mybatis.mapper.SignatureMapper;
import com.link.base.sms.model.Signature;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.ServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.*;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Author: liulu
 * @Date:15:37 2018/11/5
 */
@Service
public class SignatureServiceImpl extends BasicServiceImpl<Signature> implements SignatureService {

    @Resource
    private SignatureMapper signatureMapper;

    @Resource
    private TemplateService templateService;

    @Override
    public BasicMapper<Signature> getBasicMapper() {
        return signatureMapper;
    }

    @Override
    public void beforInsert(Signature entity) throws Exception {
        CoreUser loginUser = UserUtil.getUser();
        String smsSynToTencent = PropertyUtil.getProperty("smsSynToTencent", loginUser.getLoginCorpId());
        if ("Y".equals(smsSynToTencent)) {
            JSONObject jsonParam = new JSONObject();
            this.syncTencent(entity, "https://yun.tim.qq.com/v5/tlssmssvr/add_sign", jsonParam);
        }
    }

    @Override
    public void beforUpdate(Signature entity) throws Exception {
        CoreUser loginUser = UserUtil.getUser();
        String smsSynToTencent = PropertyUtil.getProperty("smsSynToTencent", loginUser.getLoginCorpId());
        if ("Y".equals(smsSynToTencent)) {
            if (!"notSync".equals(entity.getAttr1()) && null != entity.getSignaID()) {
                Signature signature = signatureMapper.queryById(entity);
                if (!StringUtils.isBlank(entity.getText()) && !entity.getText().equals(signature.getText())) {
                    JSONObject jsonParam = new JSONObject();
                    jsonParam.put("sign_id", entity.getSignaID());
                    this.syncTencent(entity, "https://yun.tim.qq.com/v5/tlssmssvr/mod_sign", jsonParam);
                }
            }
        }
    }

    /**
     * @author 王艳
     * @zhushi: 短信签名新增或修改时同步至腾讯云
     */
    public void syncTencent(Signature entity, String url, JSONObject jsonParam) throws Exception {
        Long time = DateUtil.getCurrentLongTime() / 1000;
        Random rd = new Random();
        String random = "";
        int rdLength = 10;
        for (int i = 0; i < rdLength; i++) {
            random += String.valueOf(rd.nextInt(10));
        }
        CoreUser loginUser = UserUtil.getUser();
        String sig = PasswordUtil.getSHA256StrJava("appkey=" + PropertyUtil.getProperty("tencentAppKey", loginUser.getLoginCorpId())
                + "&random=" + random + "&time=" + time.toString());
        jsonParam.put("sig", sig);
        jsonParam.put("text", entity.getText());
        jsonParam.put("time", time);
        String resultParams = HttpUtils.sendPost(url + "?sdkappid=" + Integer.parseInt(PropertyUtil.getProperty("tencentAppId",
                loginUser.getLoginCorpId())) + "&random=" + random, JSONObject.toJSONString(jsonParam));
        JSONObject result = JSONObject.parseObject(resultParams);

        if (result == null) {
            throw new ServiceException("SMS-004");
        } else {
            if (!"0".equals(result.get("result").toString())) {
                String errorMsg = result.getString("msg");
                throw new ServiceException(errorMsg);
            } else {
                String syncTime = DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
                String data = result.getString("data");
                JSONObject resultData = JSONObject.parseObject(data);
                // 模板 id
                String id = resultData.getString("id");

                if (!StringUtils.isBlank(id)) {
                    entity.setSignaID(Integer.valueOf(id));
                    // 更新模板状态为 待审核
                    entity.setStatus("UnderReview");
                    //entity.setSyncTime(syncTime);
                }
            }
        }
    }

    /**
     * @author 王艳
     * @zhushi: 短信签名同步腾讯云状态
     */
    @Override
    public void syncTencentStatus() throws Exception {

        List<Integer> list = signatureMapper.querySignaIDByStatus();

        if (list.size() == 0) {
            return;
        }
        Long time = DateUtil.getCurrentLongTime() / 1000;
        Random rd = new Random();
        String random = "";
        int rdLength = 10;
        for (int i = 0; i < rdLength; i++) {
            random += String.valueOf(rd.nextInt(10));
        }
        CoreUser loginUser = UserUtil.getUser();
        String sig = PasswordUtil.getSHA256StrJava("appkey=" + PropertyUtil.getProperty("tencentAppKey", loginUser.getLoginCorpId())
                + "&random=" + random + "&time=" + time.toString());
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("sig", sig);
        jsonParam.put("time", time);
        jsonParam.put("sign_id", list.toArray());
        String resultParams = HttpUtils.sendPost("https://yun.tim.qq.com/v5/tlssmssvr/get_sign?sdkappid=" + Integer.parseInt(PropertyUtil.getProperty("tencentAppId", loginUser.getLoginCorpId())) + "&random=" + random, JSONObject.toJSONString(jsonParam));
        JSONObject result = JSONObject.parseObject(resultParams);

        if (null == result) {
            throw new ServiceException("SMS-005");
        } else {
            if (!"0".equals(result.get("result").toString())) {
                String errorMsg = result.getString("msg");
                return;
            } else {
                String syncTime = DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss");
                String data = result.getString("data");
                JSONArray resultData = JSONObject.parseArray(data);
                for (Object object : resultData) {
                    JSONObject jsonObject = JSONObject.parseObject(object.toString());
                    String id = jsonObject.getString("id");
                    if (!StringUtils.isBlank(id)) {
                        Signature entity = new Signature();
                        entity.setSignaID(Integer.valueOf(id));
                        String status = jsonObject.getString("status");
                        entity.setStatus(templateService.getStatus(status));
                        /*if ("2".equals(status) && jsonObject.containsKey("reply")) {
                            String reply = jsonObject.getString("reply");
                            entity.setReply(reply);
                        }
                        entity.setSyncTime(syncTime);*/
                        signatureMapper.statusUpdate(entity);
                    }
                }
            }
        }
    }

    /**
     * @author libo
     * @desc: 删除腾讯云签名并同步删除本地数据库存储数据
     */
    @Override
    public void deleteById(Signature entity) throws Exception {
        CoreUser loginUser = UserUtil.getUser();
        String smsSynToTencent = PropertyUtil.getProperty("smsSynToTencent", loginUser.getLoginCorpId());
        //这里无论怎样都先删掉数据库中的记录（新修改的逻辑），不论是否同步到腾讯云以和同步腾讯云返回的结果是什么
        signatureMapper.deleteById(entity);
        if ("Y".equals(smsSynToTencent)) {
            if (!"notSync".equals(entity.getAttr1()) && null != entity.getSignaID()) {
                Signature signature = signatureMapper.queryById(entity);
                if (!StringUtils.isBlank(entity.getText())) {
                    JSONObject jsonParam = new JSONObject();
                    jsonParam.put("sign_id", entity.getSignaID());
                    Long time = DateUtil.getCurrentLongTime() / 1000;
                    Random rd = new Random();
                    String random = "";
                    int rdLength = 10;
                    for (int i = 0; i < rdLength; i++) {
                        random += String.valueOf(rd.nextInt(10));
                    }
                    String sig = PasswordUtil.getSHA256StrJava("appkey=" + PropertyUtil.getProperty("tencentAppKey", loginUser.getLoginCorpId())
                            + "&random=" + random + "&time=" + time.toString());
                    jsonParam.put("sig", sig);
                    jsonParam.put("time", time);
                    String resultParams = HttpUtils.sendPost("https://yun.tim.qq.com/v5/tlssmssvr/del_sign?sdkappid=" + Integer.parseInt(PropertyUtil.getProperty("tencentAppId",
                            loginUser.getLoginCorpId())) + "&random=" + random, JSONObject.toJSONString(jsonParam));
                    JSONObject result = JSONObject.parseObject(resultParams);

                    if (result == null) {
                        throw new ServiceException("SMS-009");
                    } else {
                        if (!"0".equals(result.get("result").toString())) {
                            String errorMsg = result.getString("msg");
                            throw new ServiceException("SMS-010",errorMsg);
                        } else {
//                            signatureMapper.deleteById(entity);
                        }
                    }
                }
            }
        }
    }
}
